package handler

import (
	"fmt"
	"git.oschina.net/cnjack/go-task/task"
	"html/template"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

func IndexHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	fmt.Fprintf(w, "Hello Go-Task!<br><a href=\"/tasklist\">view the task</a>|<a href=\"/addtask\">add task</a>")
}
func TaskListHandler(w http.ResponseWriter, req *http.Request) {
	var body string
	body = "当前列表:<br>"
	for _, task := range task.TaskList {
		body = body + "任务ID:" + strconv.Itoa(task.Id) + "|任务类型:" + task.TaskVaule + "|时间间隔:" + strconv.Itoa(int(task.Time)) + "|距离下次审核时间:" + strconv.Itoa(int(task.NextRunTime-time.Now().Unix())) + "<br/>"
	}
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	w.Write([]byte(body))
}
func AddTaskHandler(w http.ResponseWriter, req *http.Request) {
	t, _ := template.ParseFiles("tpl/addtask.html")
	t.Execute(w, nil)
}

type Jump struct {
	Str string
}

func AddTaskDoHandler(w http.ResponseWriter, req *http.Request) {
	var jump Jump
	t, _ := template.ParseFiles("tpl/jump.html")
	timevint, err := strconv.Atoi(req.FormValue("timev"))
	if err != nil {
		jump.Str = err.Error()
		t.Execute(w, &jump)
		return
	}
	if timevint < 10 {
		jump.Str = "间隔时间不可以小于10"
		t.Execute(w, &jump)
		return
	}
	var pass = req.FormValue("pass")
	taskType, err := strconv.Atoi(req.FormValue("taskType"))
	if err != nil {
		jump.Str = err.Error()
		t.Execute(w, &jump)
		return
	}
	var taskVaule = "http://" + req.FormValue("taskVaule")
	if taskVaule == "" {
		jump.Str = "task为空"
		t.Execute(w, &jump)
		return
	}
	//验证地址是否合法
	_, err = url.Parse(taskVaule)
	if err != nil {
		jump.Str = err.Error()
		t.Execute(w, &jump)
		return
	}
	//验证密码是否正确
	if pass != "3201" {
		jump.Str = "密码错误"
		t.Execute(w, &jump)
		return
	}
	var timev = int64(timevint)
	//添加到任务
	task.Add(timev, taskType, taskVaule)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	jump.Str = "添加成功"
	t.Execute(w, &jump)
}
func DelTaskHandler(w http.ResponseWriter, req *http.Request) {
	var id, _ = strconv.Atoi(req.FormValue("id"))
	resp := task.Del(id)
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	if resp {
		w.Write([]byte("删除成功"))
	} else {
		w.Write([]byte("id不存在"))
	}
}
